<?php

declare(strict_types=1);

namespace ImiApp\ApiServer\Backend\Service;

use Imi\Bean\Annotation\Inherit;
use ImiApp\ImiServer\AbstractService;
use Imi\Bean\Annotation\Bean;
use Imi\Aop\Annotation\Inject;
use ImiApp\ImiServer\Exception\ServiceException;
use ImiApp\ApiServer\Api\Model\Store as Model;

use ImiApp\ApiServer\Api\Model\StoreCaorder;

use Imi\Db\Db;
use Exception;
use Imi\Util\Text;
use Imi\Log\Log;

/**
 * @Inherit
 * @Bean("StoreService")
 */
class StoreService extends AbstractService
{
    /**
     * @var string
     */
    public $model = Model::class;

    /**
     * @Inject("AuthAdminService")
     *
     * @var \ImiApp\ApiServer\Backend\Service\Auth\AdminService
     */
    protected $admin_service;

    
    


    /**
     * 编辑
     * @param $data
     * @return mixed
     * @throws \Imi\Db\Exception\DbException
     */
    public function update($data)
    {

        Db::getInstance()->beginTransaction();
        try {

            $pk = $this->model::getPk();
            $pk_value = $data[$pk] ?? false;
            if (!$pk_value) {
                throw new ServiceException('未传入主键');
            }

            $res = $this->model::find($pk_value);
            if (!$res) {
                throw new ServiceException('数据不存在');
            }
            if (method_exists($this, '_before_update')) {
                $this->_before_update($data);
            }
            
            if(isset($data['apply_status']) && $data['apply_status']!='3' && $res->apply_status=='3'){
                $this->setError('拒绝后不能修改状态');
                return false;
            }

            if(isset($data['apply_status']) && $data['apply_status']!='2' && $res->apply_status=='2'){
                $this->setError('通过后不能修改状态');
                return false;
            }
            // unset($data['expire_time']);

                //判断
                if(isset($data['apply_status']) && $data['apply_status']=='2' && $res->apply_status=='1'){
                    //同意审核
                    $admin_row = $this->admin_service->model::find(['username'=>$res->mobile]);
                    if(!$admin_row){
                        $admin['avatar'] = $res->logo_image;
                        $admin['email'] = $res->mobile.'@diy.com';
                        $admin['groups'] = [3];//店铺后台
                        $admin['mobile'] = $res->mobile;
                        $admin['password'] = 'pdd123456';
                        $admin['status'] = 1;
                        $admin['username'] = $res->mobile;
                        $in_res = $this->admin_service->create($admin);
                        if($in_res){

                            try {
                                $admin_row = $this->admin_service->model::find(['username'=>$res->mobile]);
                                // var_dump('创建店铺ID:',$admin_row->id);
                            } catch (\Throwable $th) {
                                // var_dump(__METHOD__,$th->getMessage());
                            }
                            // var_dump('ID:',$this->admin_service->model->id);
                            
                        }else{
                            var_dump(__METHOD__,$this->admin_service->getError());
                        }
                        
                        
                    }

                    
                    //店铺认证通过
          
                    $StoreBean = new \ImiApp\ApiServer\Api\Controller\store\StoreBean;
                    $StoreBean->StoreApplyPass($res->id);


                    $data['expire_time'] = $StoreBean->getStoreApplyPassExpireTime($res->id);

                    Log::info('店铺认证通过:'.$res->id.'adminID:'.$admin_row->id);
                    // var_dump('店铺adminID:',$admin_row->id);
                }elseif(isset($data['apply_status']) && $data['apply_status']=='3' && $res->apply_status=='1'){
                //拒绝通过 
                    //查询认证的钱
                    $StoreCaorder = StoreCaorder::dbQuery()
                                    ->where('store_id','=',$res->id)
                                    ->where('pay_status','=','2')
                                    ->find();//->order('pay_time','desc')

                    if(!$StoreCaorder){
                        Log::error('店铺认证拒绝退费用'.$res->id.'没找到认证金');
                    }else{
                        $money = $StoreCaorder['money'];

                        // 退钱
                        $tpmecms = new \ImiApp\ApiServer\Api\Controller\Tpmecms;
                        $tpmecms->inc_user_money($res->user_id,$money,'店铺认证拒绝退费用',CODE_店铺认证拒绝退费用,$StoreCaorder['id']);
                        StoreCaorder::dbQuery()
                                    ->where('id','=',$StoreCaorder['id'])
                                    ->update(['pay_status'=>'3']);
            
                    }
    
                }
            //结束
            $key = $data[$pk];
            unset($data[$pk]);
            var_dump('data',$data);

            foreach ($data as $field => $val) {
                $setname = 'set' . Text::toPascalName($field);

                $res->$setname($val);
            }
            $res->update();
            // $this->model->update();
            // $res->update($data);
            if (method_exists($this, '_after_update')) {
                $this->_after_update($key, $res);
            }
            Db::getInstance()->commit();
        } catch (ServiceException $e) {
            Db::getInstance()->rollBack();
            $this->setError($e->getMessage());
            return false;
        } catch (Exception $e) {
            Db::getInstance()->rollBack();
            Log::error($e);
            return false;
        }
        
        return true;
    }
}
